import Vue from 'vue'
import Vuex from 'vuex'
 
Vue.use(Vuex)

import service from '@/service.js'

var SocketUrl = service.FOX_SOKET;
 
export default new Vuex.Store({
	state: {
		socketTask: null, // ws链接
		webSocketPingTimer: null, // 心跳定时器
		webSocketPingTime: 20000, // 心跳的间隔，当前为 25秒,
		webSocketReconnectCount: 0, // 重连次数
		webSocketReconnectCountNum: 3000, // 最大重连次数
		webSocketIsReconnect: true, // 是否重连
		webSocketIsOpen: false,
		webOrderOpen: false,
		webOrderOpenl: false,
		webchatOpenc: false,
		sendMsgStatus: false,
		user_key: null, //ws登录user_key
		ma_type: null,
		chat_type: null,
		order_position: null,
		order_id: null,
		ma_id: null,
		uid: null,
		touid: null,
		user_name: null,
		content: null,
		user_tel: null,
		index: null,
		msg: null //接收到的信息
	},
	getters: {
		// 获取接收的信息
		socketMsgs: state => {
			return state.msg
		},
		sendStatus: state => {
			return state.sendMsgStatus
		},
		socketIsOpen: state => {
			return state.webSocketIsOpen
		},
		orderOpen: state => {
			return state.webOrderOpenl
		},
		orderOpenl: state => {
			return state.webOrderOpenl
		},
		chatOpenc: state => {
			return state.webchatOpenc
		}
	},
	mutations: {
		//发送http请求登录后设置用户user_key
		setUser_key(state, user_key) {
			state.user_key = user_key
		},
		setMa_type(state, ma_type) {
			state.ma_type = ma_type
		},
		setChat_type(state, chat_type) {
			state.chat_type = chat_type
		},
		setOrder_position(state, order_position) {
			state.order_position = order_position
		},
		setOrder_id(state, order_id) {
			state.order_id = order_id
		},
		setMa_id(state, ma_id) {
			state.ma_id = ma_id
		},
		setUid(state, uid) {
			state.uid = uid
		},
		setTouid(state, touid) {
			state.touid = touid
		},
		setUser_name(state, user_name) {
			state.user_name = user_name
		},
		setUser_tel(state, user_tel) {
			state.user_tel = user_tel
		},
		setContent(state, content) {
			state.content = content
		},
		setIndex(state, index) {
			state.index = index
		},
		//初始化ws 用户登录后调用
		webSocketInit(state) {
			let that = this
			// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
			state.socketTask = uni.connectSocket({
				url: SocketUrl,
				success(data) {
					console.log("websocket连接成功");
				},
			});
 
			// ws连接开启后登录验证
			state.socketTask.onOpen((res) => {
				console.log("WebSocket连接正常打开中...！");
				//开始心跳
				// that.commit('webSocketUser')
				that.commit('webSocketPing')
				// 注：只有连接正常打开中 ，才能正常收到消息
				state.socketTask.onMessage((res) => {
					console.log("收到服务器内容");
					// console.log("收到服务器内容：" + res.data);
					that.state.msg = JSON.parse(res.data)
					that.state.sendMsgStatus = true
				});
 
			});
 
			// 链接开启后登录验证
			state.socketTask.onError((errMsg) => {
				console.log(errMsg)
				console.log("ws连接异常")
				that.commit('webSocketClose')
			});
 
			// 链接开启后登录验证
			state.socketTask.onClose((errMsg) => {
				console.log(errMsg)
				console.log("ws连接关闭")
				that.commit('webSocketClose')
			});
 
		},
		
		//用户查询
		webSocketUser() {
			let that = this
			let info = service.getfox();
			console.log("ws用户");
			const payload = {
				user_key: info[0]['foxtoken'],
				type: 'userinfo'
			};
			that.commit('webSocketSend', payload);
			that.state.webSocketIsOpen = true;
		},
		//寻找订单
		webSocketOrder() {
			let that = this
			console.log("ws订单");
			const payload = {
				user_key: that.state.user_key,
				ma_type: that.state.ma_type,
				order_position: that.state.order_position,
				type: 'order'
			};
			that.commit('webSocketSend', payload);
			that.state.webSocketIsOpen = true;
			that.state.webOrderOpen = true;
		},
 
		//停止接收订单
		webSocketOrder_shut(state) {
			let that = this
			that.state.webOrderOpen = false;
		},
		//抢单
		webSocketGrab() {
			let that = this
			console.log("ws抢单");
			const payload = {
				user_key: that.state.user_key,
				ma_id: that.state.ma_id,
				order_id: that.state.order_id,
				ma_type: that.state.ma_type,
				uid: that.state.uid,
				user_tel: that.state.user_tel,
				index: that.state.index,
				type: 'grab'
			};
			that.commit('webSocketSend', payload);
			that.state.webSocketIsOpen = true;
			that.state.webOrderOpen = true;
		},
		//寻找已抢
		webSocketOrderl() {
			let that = this
			console.log("ws已抢");
			const payload = {
				user_key: that.state.user_key,
				type: 'listorder'
			};
			that.commit('webSocketSend', payload);
			that.state.webSocketIsOpen = true;
			that.state.webOrderOpenl = true;
		},
		//寻找聊天
		webSocketChatlist() {
			let that = this
			console.log("ws聊天");
			const payload = {
				user_key: that.state.user_key,
				uid: that.state.uid,
				type: 'listchat'
			};
			that.commit('webSocketSend', payload);
			that.state.webSocketIsOpen = true;
			that.state.webchatOpenc = true;
		},
		
		//添加聊天
		webSocketChatadd() {
			let that = this
			console.log("ws聊天发送");
			const payload = {
				user_key: that.state.user_key,
				uid: that.state.uid,
				user_name: that.state.user_name,
				touid: that.state.touid,
				chat_type: that.state.chat_type,
				content: that.state.content,
				type: 'addchat'
			};
			that.commit('webSocketSend', payload);
			that.state.webSocketIsOpen = true;
			that.state.webchatOpenc = true;
		},
		 
		//停止接收抢单
		webSocketOrderl_shut(state) {
			let that = this
			that.state.webOrderOpenl = false;
		},
		// 断开连接时
		webSocketClose(state) {
			let that = this
			// 修改状态为未连接
			state.webSocketIsOpen = false;
			state.webSocket = null;
			// 判断是否重连
			if (
				state.webSocketIsReconnect &&
				state.webSocketReconnectCount === 0
			) {
				// 第一次直接尝试重连
				that.commit('webSocketReconnect');
			}
		},
 
		// 定时心跳
		webSocketPing() {
			let that = this
			that.state.webSocketPingTimer = setTimeout(() => {
				if (!that.state.webSocketIsOpen) {
					return false;
				}
				console.log("心跳");
				const payload = {
					type: 'ping'
				};
				that.commit('webSocketSend', payload);
				clearTimeout(that.state.webSocketPingTimer);
				// 重新执行
				that.commit('webSocketPing');
			}, that.state.webSocketPingTime);
		},
		// WebSocket 重连
		webSocketReconnect(state) {
			let that = this
			if (state.webSocketIsOpen) {
				return false;
			}
			console.log("第"+state.webSocketReconnectCount+"次重连")
			state.webSocketReconnectCount += 1;
			// 判断是否到了最大重连次数 
			if (state.webSocketReconnectCount >= state.webSocketReconnectCountNum) {
				this.webSocketWarningText = "重连次数超限";
			    return false;
			}
			// 初始化
			console.log("开始重连")
			that.commit('webSocketInit');
 
			// 每过 5 秒尝试一次，检查是否连接成功，直到超过最大重连次数
			let timer = setTimeout(() => {
				that.commit('webSocketReconnect');
				clearTimeout(timer);
			}, 10000);
		},
 
		// 发送ws消息
		webSocketSend(state, payload) {
			let that = this
			// console.log(JSON.stringify(payload))
			that.state.socketTask.send({
				data: JSON.stringify(payload),
				fail: function(res){
					that.state.sendMsgStatus = false
					console.log("发送失败")
				},
				success: function(res){
					// that.state.sendMsgStatus = true
					console.log("发送成功")
				}	
			})
		}
	},
 
 
	actions: {
		webSocketInit({
			commit
		}, url) {
			commit('webSocketInit', url)
		},
		webSocketSend({
			commit
		}, p) {
			commit('webSocketSend', p)
		}
	}
})